// page/details/pages/aplicationCard/aplicationCard.js
const utils = require('../../../../utils/util.js');
let myRequest = require('../../../../common/script/myRequest.js');
let api = require('../../../../common/script/api.js');
let login = require('../../../../common/script/login');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      phone: '请选择手机号码',
      phone_sign: '',
      code: '',
      idcard: '',
      recode: ''
    },
    type: false,
    provinceName: "",
    province_code: "",
    provinceIndex: "",
    shopName: "",
    orgIndex: "",
    org_code: "",
    provinceList: null,
    shopList: null,
    provinceListData: null,
    shopListData: null,
    shopData: null,
    teamer_id: "",
    isnoshowCard: true
  },
  getData(options) {
    const that = this;
    let sceneObj = null;
    if (options.type) {
      that.setData({
        type: true
      })
      utils.getLocation().then(res => {
        that.getShop(res)
      }).catch(err => {
        wx.showModal({
          content: '无法获取定位，请联系店员扫码申请！',
          cancelText: "返回",
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定')
              wx.scanCode({
                success: (res) => {
                  console.log(res, 787878)
                  let scene = decodeURIComponent(res.result)
                  const url = scene.substring(scene.indexOf('?') + 1)
                  const params = url.split('&')
                    .reduce(function (acc, param) {
                      const [key, value] = param.split('=');
                      acc[key] = decodeURIComponent(value);
                      return acc;
                    }, {});
                    console.log(params,8888)

                  let recode = params['recode'];
                  let orgcode = params['orgcode'];
                  that.setData({
                    [`formData.recode`]: recode,
                    org_code: orgcode
                  })
                  
                  that.getShop({
                    latitude: '',
                    longitude: ''
                  })
                }
              })
            } else if (res.cancel) {
              wx.navigateBack({
                delta: 1
              })
              console.log('用户点击取消')
            }
          }
        })
      })
    } else {
      if (options.scene) {
        sceneObj = utils.parseQueryString(options.scene)
        console.log(sceneObj, 8888899)
        if (sceneObj.recode) {
          that.setData({
            [`formData.recode`]: sceneObj.recode ? sceneObj.recode : '',
            org_code: sceneObj.orgcode ? sceneObj.orgcode : ''
          })
        } else {
          that.setData({
            [`formData.recode`]: sceneObj.recode ? sceneObj.recode : '',
            org_code: sceneObj.org_code ? sceneObj.org_code : ''
          })
        }
      } else {
        console.log(options.q,7878787878)
        let scene = decodeURIComponent(options.q)
        const url = scene.substring(scene.indexOf('?') + 1)
        const params = url.split('&')
          .reduce(function (acc, param) {
            const [key, value] = param.split('=');
            acc[key] = decodeURIComponent(value);
            return acc;
          }, {});
        let recode = params['recode'];
        let orgcode = params['orgcode'];

        that.setData({
          [`formData.recode`]: recode,
          org_code: orgcode
        })
      }


      that.getShop({
        latitude: '',
        longitude: ''
      })
    }

  },
  //获取店铺
  getShop(prop) {
    const that = this;
    let data = {
      lat: prop.latitude,
      lng: prop.longitude,
      org_code: that.data.org_code,
      recode: that.data.formData.recode,
      token: wx.getStorageSync('token')
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.getShopList, data).then(res => {
      wx.hideLoading();
      if (res.data.status == 1) {
        let provinceList = []
        let shopList = []
        let provinceListData = []
        let shopListData = []
        res.data.result.forEach((prop, index) => {
          if (prop.province_info.select == 1) {
            that.setData({
              provinceName: prop.province_info.province_name,
              province_code: prop.province_info.province_code,
              provinceIndex: index,
              shopName: prop.store_list[0].name,

            })
            prop.store_list.forEach((item, indexs) => {
              if (item.select == 1) {
                that.setData({
                  shopName: item.name,
                  orgIndex: indexs,
                  org_code: item.erp_store_code
                })
              }
              shopList.push(item.name)
              shopListData.push({
                name: item.name,
                code: item.erp_store_code
              })
            })
          }
          provinceList.push(
            prop.province_info.province_name
          )
          provinceListData.push({
            name: prop.province_info.province_name,
            code: prop.province_info.province_code,
          })
        })
        that.setData({
          provinceList,
          shopList,
          provinceListData,
          shopListData,
          shopData: res.data.result
        })
      } else {
        wx.showModal({
          content: res.data.msg,
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#ff5151',
          success(e) {}
        })
      }
    })
  },
  bindShop(e) {
    const that = this;
    let index = e.detail.value
    let shopName = that.data.shopListData[index].name
    let org_code = that.data.shopListData[index].code
    that.setData({
      shopName,
      org_code
    })
  },
  bindProvince(e) {
    const that = this;
    let shopList = []
    let shopListData = []
    let index = e.detail.value
    let provinceName = that.data.provinceListData[index].name
    let province_code = that.data.provinceListData[index].code
    that.data.shopData[index].store_list.forEach((item, indexs) => {
      shopList.push(item.name)
      shopListData.push({
        name: item.name,
        code: item.erp_store_code
      })
    })
    that.setData({
      shopName: '请选择店铺',
      org_code: '',
      shopList,
      shopListData,
      provinceName,
      province_code
    })
  },
  // 获取推荐码
  getRecode(e) {
    const that = this;
    that.setData({
      [`formData.recode`]: e.detail.value
    })
  },
  // 获取手机号
  getPhoneNumber(e) {
    const that = this;
    let dataType = e.currentTarget.dataset.type
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.login({
        success: function (res) {
          if (res.errMsg == "login:ok") {
            let data = {
              token: wx.getStorageSync('token'),
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv,
              code: res.code
            }
            wx.showLoading({
              title: '加载中...',
            })
            myRequest.EasyHttp.post(api.reqUrls.getMiniPhoneNoBind, data).then(res => {
              wx.hideLoading();
              if (res.data.status == 1) {
                that.setData({
                  'formData.phone': res.data.result.mobile,
                  'formData.phone_sign': res.data.result.phone_sign
                })
                if (dataType == 2) {
                  that.Apply()
                }
              } else {
                wx.showModal({
                  content: res.data.msg,
                  showCancel: false,
                  confirmText: '我知道了',
                  confirmColor: '#ff5151',
                  success(e) {}
                })
              }
            })
          }
        }
      })

    }
  },

  //是否已经有会员卡
  getMemberCard() {
    const that = this;
    let data = {
      token: wx.getStorageSync('token'),
    }
    myRequest.EasyHttp.post(api.reqUrls.membercardShow, data).then(res => {
      if (res.data.status == 1) {
        that.setData({
          isnoshowCard: true,
        })
      } else if (res.data.status == -2) {
        that.setData({
          isnoshowCard: false
        })
      }
    })
  },
  // 申请会员卡
  Apply() {
    const that = this;
    if (!that.data.province_code) {
      wx.showToast({
        title: "请选择省"
      })
      return;
    }
    if (!that.data.org_code) {
      wx.showToast({
        title: "请选择店铺"
      })
      return;
    }
    if (!that.data.formData.phone_sign) {
      wx.showToast({
        title: "请选择手机号码"
      })
      return;
    }
    that.ApplyFun()
  },
  ApplyFun() {
    const that = this;

    let data = {
      org_code: that.data.org_code,
      province_code: that.data.province_code,
      token: wx.getStorageSync('token'),
      unique_id: wx.getStorageSync('token'),
      // org_code: '1111048',
      // province_code: '001',
      phone: that.data.formData.phone,
      phone_sign: that.data.formData.phone_sign,
      code: that.data.formData.code,
      idcard: that.data.formData.idcard,
      recode: that.data.formData.recode,
      bind: 0
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.createVirtualMember, data).then(res => {
      wx.hideLoading();
      if (res.data.status == 1) {
        //返回tab页面刷新数据
        wx.setStorageSync('refresh', true)

        wx.showModal({
          content: res.data.msg,
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#ff5151',
          success(e) {
            if (that.data.teamer_id) {
              wx.redirectTo({
                url: `/page/details/pages/deputyLeader/deputyLeader?teamer_id=${that.data.teamer_id}`
              })
            } else {
              if (that.data.type) {
                wx.navigateBack({
                  delta: 1
                })
              } else {
                wx.switchTab({
                  url: '/pages/index/index'
                })
              }
            }
          }
        })
      } else {
        wx.showModal({
          content: res.data.msg,
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#ff5151',
          success(e) {}
        })
      }
    }).catch(err => {
      console.log(err)
      wx.showToast({
        title: '服务器错误',
        icon: 'error',
        duration: 2000
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;
    login.checkLogin().then(res => {
      if (options.teamer_id) {
        that.setData({
          teamer_id: options.teamer_id
        })
      }
      that.getData(options)
      // that.getMemberCard()
    }).catch(err => {
      app.appCallBack = (e) => {
        if (options.teamer_id) {
          that.setData({
            teamer_id: options.teamer_id
          })
        }
        that.getData(options)
        // that.getMemberCard()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage() {

  // }
})